package com.hemi.rhet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.http.ParseException;
import org.apache.http.cookie.Cookie;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.HttpUtil;
import com.hemi.rhet.util.OSInfoUtil;

public class WebViewDemo extends Activity {   
	  
    private static final String LOG_TAG = "WebViewDemo";   
  
    private static final int reply_call_carema = 100;  
    
    private WebView mWebView;   
  
    private String defaultUrl = HttpUtil.buildUrl("/post/myPostes");
    @Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
    	 
		return super.onCreateDialog(id);
	}

	private Handler mHandler = new Handler();   
  
	  private static final int SCTU = Menu.FIRST;
	    private static final int FB = Menu.FIRST + 1;
	    private static final int BACK_ID = Menu.FIRST + 3;
	    private static final int FROM_ALARM = Menu.FIRST + 5;
    @Override  
    public void onCreate(Bundle icicle) { 
    	OSInfoUtil.version4Adapter();
        super.onCreate(icicle);   
        setContentView(R.layout.web_post);   
        mWebView = (WebView) findViewById(R.id.postdispalyview); 
        WebSettings webSettings = mWebView.getSettings();   
        webSettings.setDefaultTextEncodingName("utf-8"); 
        webSettings.setSavePassword(false);   
        webSettings.setSaveFormData(false);   
        webSettings.setJavaScriptEnabled(true);   
        webSettings.setSupportZoom(false);   
        webSettings.setBuiltInZoomControls(false);
        mWebView.setWebChromeClient(new MyWebChromeClient());  
        mWebView.setInitialScale(100);//初始显示比例100%
        mWebView.setMinimumHeight(100);
        mWebView.setMinimumWidth(100);
        JavaScriptInterfaceBinder.INSTANCE.addCallCaremaAblity(this, mWebView, mHandler);
        JavaScriptInterfaceBinder.INSTANCE.addWebDataPostAblity(this, mWebView, mHandler);
        JavaScriptInterfaceBinder.INSTANCE.addWebDataUrlRedirectAblity(this, mWebView, mHandler);
        JavaScriptInterfaceBinder.INSTANCE.addWebImageSelectAblity(this, mWebView, mHandler);
        String key = getIntent().getStringExtra("currentTabTag");
        
        mWebView.loadUrl(defaultUrl);   
    }   
  
    private String imageContainerId = null;
    private String fileIdItemName = null;
    
    public boolean callCarema(){
    	Intent i= new Intent();
		i.setClass(WebViewDemo.this, PhotoUpload.class);
		startActivityForResult(i,SCTU);
		return true;
    }
    
    final class JavaScriptInterfaceCallCarema {   
        public void clickOnAndroid(final String imageContainerIdp,final String fileIdItemNamep) { 
//        	imageContainerId  = imageContainerIdp;
//        	fileIdItemName = fileIdItemNamep;
//        	Intent i= new Intent();
//    		i.setClass(WebViewDemo.this, PhotoUpload.class);
//    		startActivityForResult(i,SCTU);
    		
    		
            mHandler.post(new Runnable() {   
                public void run() {   
                	imageContainerId  = imageContainerIdp;
                	fileIdItemName = fileIdItemNamep;
                	callCarema();
                }   
            });   
        }   
    }   
    
    
//    final class JavaScriptInterface2PostGuide {   
//        public void clickOnAndroid(final String postDetailUrl) {   
//            mHandler.post(new Runnable() {   
//                public void run() {   
//                	  Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
//                      CookieSyncManager.createInstance(WebViewDemo.this);  
//                      CookieManager cookieManager = CookieManager.getInstance();  
//                      if (sessionCookie != null) {  
//                          String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
//                          cookieManager.setCookie(Constants._COOKIE_KEY, cookieString);  
//                          cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
//                          CookieSyncManager.getInstance().sync();  
//                      }
////                      Intent i = new Intent(WebViewDemo.this, PostDetailGuide.class);
//                      history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(postDetailUrl);
////                      i.putExtra(Constants._POST_GUIDE_KEY_, history_url);
////                      startActivity(i);	
//                      
//                      mWebView.loadUrl(history_url); 
//                      
//                }   
//            });   
//        }   
//    } 
    
    

    class JavaScriptInterface2URL {
      public void clickOnAndroid(final String url) {   
    	
          
    	  mHandler.post(new Runnable() {   
              public void run() {   
                  String url2 = HttpUtil.buildUrl(url);
//		             if(url2.indexOf("?")==-1)
//		             {
//		            	 url2 = url2+"?currentUserId="+currentUserId;
//		             }else{
//		            	 url2 = url2+"&currentUserId="+currentUserId;
//		             }
            	  mWebView.loadUrl(url2); 
              }});   
      }   
    	  
      
  }
  
  

class JavaScriptInterface4POSTDataHttpClient {
//	private Context contxt = null;
//	private WebView mWebView = null;
//	public JavaScriptInterface4POSTDataHttpClient(Context contxt, WebView mWebView)
//	
//	{
//		this.mWebView = mWebView;
//		this.contxt = contxt;
//	}
	
  public void clickOnAndroid(final String url,final String content) {  
  	 mHandler.post(new Runnable() {   
           public void run() { 
      	 String urlStr =	HttpUtil.buildUrl(url);
    		 	 HashMap mapparams = new HashMap();
    		 	try {
    		 		JSONObject d = new JSONObject(content);
					Iterator it = d.keys();
					while(it.hasNext())
					{
						String key  =(String)it.next();
						String value = (String)d.get(key);
						mapparams.put(key, value);
					}
					
//					mapparams.put("currentUserId",currentUserId);
					HashMap rcontent = HttpUtil.postUrl4ResultMap(urlStr, mapparams);
					if(rcontent!=null && rcontent.get("code")!=null && rcontent.get("code").equals("1"))
					{
			             String url = HttpUtil.buildUrl(mapparams.get("_redirectUrl_")+"");
//			             if(url.indexOf("?")==-1)
//			             {
//			            	 url = url+"?currentUserId="+currentUserId;
//			             }else{
//			            	 url = url+"&currentUserId="+currentUserId;
//			             }
			             mWebView.loadUrl(url); 
//						 mWebView.loadUrl("http://192.168.1.118:8080/aiu/post/myPostes_android");   
					}else{
						Toast.makeText(WebViewDemo.this, "操作失败！",Toast.LENGTH_SHORT).show();   
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} 
           }
  	 });  
  }


}


    
    
//    final class JavaScriptInterface2URL {   
//        public void clickOnAndroid(final String url) {   
//        	 Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
//             CookieSyncManager.createInstance(WebViewDemo.this);  
//             CookieManager cookieManager = CookieManager.getInstance();  
//             if (sessionCookie != null) {  
//                 String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
////                 cookieManager.setCookie(Constants._COOKIE_KEY, cookieString);  
//                 cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
//                 CookieSyncManager.getInstance().sync();  
//             }
//       	history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(url);
//       	 mWebView.loadUrl(history_url); 
//        }   
//    }   
    
    
     
    
    
//    
//    final class JavaScriptInterface4POSTDataHttpClient {   
//        public void clickOnAndroid(final String url,final String content) {  
//        	 mHandler.post(new Runnable() {   
//                 public void run() { 
//            	 String urlStr = new StringBuffer(ApplicationContext.DOMAIN+url+"_android").toString();
//          		 	 HashMap mapparams = new HashMap();
//          		 	try {
//          		 		JSONObject d = new JSONObject(content);
//						Iterator it = d.keys();
//						while(it.hasNext())
//						{
//							String key  =(String)it.next();
//							String value = (String)d.get(key);
//							mapparams.put(key, value);
//						}
//						HashMap rcontent = HttpUtil.postUrl4ResultMap(urlStr, mapparams);
//						if(rcontent!=null && rcontent.get("code").equals("1"))
//						{
//							Toast.makeText(WebViewDemo.this, "操作成功！",Toast.LENGTH_SHORT).show();    
//							
//				        	 Cookie sessionCookie = (Cookie) ApplicationContext.getData(Constants._COOKIE_KEY);//这里的cookie就是上面保存的cookie    
//				             CookieSyncManager.createInstance(WebViewDemo.this);  
//				             CookieManager cookieManager = CookieManager.getInstance();  
//				             if (sessionCookie != null) {  
//				                 String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
////				                 cookieManager.setCookie(Constants._COOKIE_KEY, cookieString);  
//				                 cookieManager.setCookie(ApplicationContext.DOMAIN, cookieString);
//				                 CookieSyncManager.getInstance().sync();  
//				             }
//				             history_url = ApplicationContext.DOMAIN+OSInfoUtil.trAppNameUrl(mapparams.get("_redirectUrl_")+"_android");
//							 mWebView.loadUrl("http://192.168.1.118:8080/aiu/post/myPostes_android");   
//						}else{
//							Toast.makeText(WebViewDemo.this, "操作失败！",Toast.LENGTH_SHORT).show();   
//						}
//					} catch (JSONException e) {
//						e.printStackTrace();
//					} catch (ParseException e) {
//						e.printStackTrace();
//					} catch (IOException e) {
//						e.printStackTrace();
//					} 
//                 }
//        	 });  
//        }
//    }  
    
    
 


  
    
    
   
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
//        menu.add(0, SCTU,0, R.string.sctp);
//        menu.add(0,FB,0, R.string.fb);
        return true;
    }
	
    //@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	boolean result = true;
        switch(item.getItemId()) {
        case SCTU:
			Intent i= new Intent();
			i.setClass(WebViewDemo.this, PhotoUpload.class);
			startActivityForResult(i,SCTU);
			result = true;
			break;
        case FB:
        	ParamUtil.showMessage(WebViewDemo.this, "发表中...");
        	mWebView.loadUrl("javascript:issureArticle()");
        	result = true;
        	break;
		default:
			result = super.onMenuItemSelected(featureId, item);
			break;
		}
        return result; 
    }
    
    
    

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
			if(data==null)
			{
				ParamUtil.showMessage(WebViewDemo.this, "无图片选择！");
				return ;
			}
			String message = (String)data.getExtras().get("imageInfo");
			HashMap ham = ParamUtil.stringTomsgMap(message);
			mWebView.loadUrl("javascript:createImageSrc('"+ham.get("fileId")+"','"+ham.get("fileName")+"','"+imageContainerId+"','"+fileIdItemName+"')");
	}
	@Override
	public void onAttachedToWindow() {
	     super.onAttachedToWindow();
	     openOptionsMenu();
	} 

	/**  
     * Provides a hook for calling "alert" from javascript. Useful for  
     * debugging your javascript.  
     */  
    final class MyWebChromeClient extends WebChromeClient {   
        @Override  
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {   
            Log.d(LOG_TAG, message);   
            result.confirm();   
            return true;   
        }   
           
    }   
}  
